import React, { useState, useEffect, useMemo } from 'react';
import s from './style.module.css';
import Helper from '../../../components/Helper';
import SecurityRating from './SecurityRating';
import { IconS } from './SecurityRating/picture';
import PropTypes from 'prop-types';
import Label from '../../../components/Label';
import KDialog from '@knownsec/react-component/dist/Dialog';
import Progress from '@knownsec/react-component/dist/Progress';
import Message from '@knownsec/react-component/dist/Message';
import { Menu, Dropdown } from 'antd';
import fetchFer from 'API/fetch';
import { Link } from 'react-router-dom';
import Select from '@knownsec/react-component/dist/Select';
import { datetime } from '../../../../common/formatter';
import Tabs, { TabPane } from '@kuiper-components/tabs';
import {
	turnToUrlparam,
	GetQueryString,
	GetQueryObject,
} from '../../../helpers/getUrlParams';
import SequenceDialog, { SequenceIcon } from '../../../components/SequenceDialog';
import EmptyData from '../../../components/empty/EmptyData';
import moment from 'moment';
import cn from 'classnames';
import w from '../Jobs/style.module.css';
import Info from './webPane/info';
import Change from './webPane/change';
import VulTable from './webPane/VulTable';
import SSLTable from './webPane/SSLTable';
import SecurityTable from './webPane/SecurityTable';
import ContentTable from './webPane/ContentTable';
import Available from './webPane/aviliable';
import ChangeCheckTable from './webPane/ChangeCheckTable';
import WafErrorDialog from '../../../components/WafErrorDialog';
import UrlDetailDialog from '../../../components/UrlDetailDialog';
import Tooltip from '@knownsec/react-component/dist/Tooltip';
import Icon from '@knownsec/react-component/dist/Icon';
const infoObj = {
	note: '资产名称',
	source_ip: '源站IP',
	target_url: '资产地址',
	// target_status: <span>网站状态<Tooltip placement='top' overlay='最近一次监测任务的网络检测结果'><Icon type='question' className={'cp'} /></Tooltip></span>
};
const statusMap = {
	http_waf_error:
		<>
			ScanV扫描节点疑似被目标主机防火墙拦截，建议将
			<WafErrorDialog className={'lh20 h20'} />
			加白再进行检测。
		</>,
	http_status_error: '平台探测到疑似网站状态异常，建议检查网站状态。',
	http_code_error: '平台探测到网站状态码异常，建议检查网站状态。',
	ping_error: '平台探测到疑似目标主机服务异常，建议检查服务状态。',
};

function JobDetail({ assetType, row, location, history }) {
	const TabsKey = GetQueryString(location.search, 'TabsKey');
	const hisChangeTaskId = GetQueryString(location.search, 'task_id');
	const [detail, setDetail] = useState({});
	const [activeKey, setActiveKey] = useState(TabsKey || 'vul');
	const [refresh, setRefresh] = useState(false)
	const getWebDetail = async () => {
		const sendData = {
			job_id: row?.job_id,
		};
		const params = turnToUrlparam(sendData);
		const res = await fetchFer(`/api/v2/tasks/web/detail/summary?${params}`, {
			method: 'GET',
		}).catch(error => {
			return null;
		});
		const total = Object.values(res.results.warning_count_map).reduce(
			(t, i) => {
				t += i;
				return t;
			},
			0
		);
		let result = `发现`;
		result += `${res?.results?.warning_count_map?.vul || 0}个Web漏洞，`;
		result += `${res?.results?.warning_count_map?.ssl || 0}个SSL安全威胁，`;
		result += `${res?.results?.warning_count_map?.security_event}个安全事件，`;
		result += `${res?.results?.warning_count_map?.content}个内容违规事件，`;
		result += `${res?.results?.warning_count_map?.change_check}个篡改事件，`;
		result += '为了您的资产安全，请及时修复并加固安全防护。';
		setDetail(
			{
				...res.results,
				result: (res.results.is_display_url ? `检测${res.results.url_count}个URL地址，` : '') +
					(total
						? result
								: '本次检测未发现任何风险，您的Web资产处于安全状态。'),
			} || {}
		);
		setRefresh(false)
	};
	// 变动
	const resDemo = e => {
		const aa = e && e?.replace(/\d+/g, `<span style='color: #EA0028'>$&</span>`);
		return aa;
	};
	const downloadTimer = React.useRef();
	const [isDownload, setIsDownload] = useState(true);
	const [downloadTaskId, setDownloadTaskId] = useState('');
	const [progressVisible, setProgressVisible] = useState(false);
	const [downloadPercent, setDownloadPercent] = useState(0);

	const downloadReport = () => {
		if (!isDownload) return false;
		setIsDownload(false);
		fetchFer(`/api/v2/report/download_task`, {
			method: 'POST',
			body: JSON.stringify({
				download_type: '1',
				job_ids: row?.job_id,
				report_type: 'latest',
				file_type: 'docx'
			}),
		})
			.then(res => {
				if (res.code === 200) {
					setIsDownload(true);
					setDownloadPercent(0);
					setProgressVisible(true);
					setDownloadTaskId(res.result.download_task_id);
					downloadTimer.current = setInterval(() => {
						getProgress(res.result.download_task_id, [row?.note], 0);
					}, 1000);
				} else {
					setIsDownload(true);
				}
			})
			.catch(e => {
				setIsDownload(true);
				return {};
			});
	};
	const getProgress = (id, name, type) => {
		fetchFer(`/api/v2/report/download_progress?download_task_id=${id}`)
			.then(res => {
				if (res.code === 200) {
					if (res.result.progress === 100) {
						setDownloadPercent(99);
						clearInterval(downloadTimer.current);
						fetch(`/api/v2/report/download_completed?download_task_id=${id}`)
							.then(res => {
								if (res.ok) {
									return res.blob();
								}
							})
							.then(blob => {
								const url = (window.webkitURL || window.URL).createObjectURL(
									blob
								);
								const a = document.createElement('a');
								if (type === 0) {
									a.download = `[${
										name[0] +
										(name.length > 1 ? '等多个资产' : '') +
										(name.length > 1 && type === 0 ? '汇总' : '')
									}]ScanV安全监测报告.docx`;
								} else {
									a.download = `[${
										name[0] +
										(name.length > 1 ? '等多个资产' : '') +
										(name.length > 1 && type === 0 ? '汇总' : '')
									}]ScanV安全监测报告.zip`;
								}
								a.href = url;
								setDownloadPercent(100);
								setTimeout(function () {
									setProgressVisible(false);
									a.click();
								}, 500);
							})
							.catch(error => {
								return {};
							});
					} else {
						setDownloadPercent(res.result.progress);
					}
				} else {
					clearInterval(downloadTimer.current);
				}
			})
			.catch(error => {
				setProgressVisible(false);
				clearInterval(downloadTimer.current);
				setDownloadPercent(0);
				Message.show({
					type: 'error',
					message: error.message,
				});
			});
	};
	const changeTabs = e => {
		const search = GetQueryObject(location.search);
		const sendData = {
			...search,
			TabsKey: e,
		};
		const params = turnToUrlparam(sendData);
		history.replace(`${location.pathname}?${params}`);
		setActiveKey(e);
	};
	const getTableTip = (data, title) => {
		let text = '暂无数据'
		let img = 'noData'
		if (data?.target_status?.status !== 'good') {
			text = <span>暂无数据，当前监测任务异常<SequenceDialog className={'ml5'} target_status={{
				http: {...data?.target_status?.httpGetSequence, target_status: data?.target_status?.status },
				ping: {...data?.target_status?.detailPing, target_status: data?.target_status?.status },
			}} title={title + '网络快照'}
			subTitle=''
			url_count={data?.overview?.url_count} statusText={statusMap[data?.target_status?.status] ? data?.target_status?.status : (data?.target_status?.status === 'good' ? '正常' : '')} /></span>
			img = 'noData'
		}
		return { text, img }
	}
	useEffect(() => {
		if (refresh) {
			getWebDetail();
		}
	}, [refresh])
	useEffect(() => {
		getWebDetail();
		return () => {
			clearInterval(downloadTimer.current);
		}
	}, []);
	return (
		<div className={cn(s.content, s.pr)}>
			{row?.job_id && (
				<div className={cn(s.timeType, s.tar, s.mb10)}>
					<div
						className={cn(s.primaryColor, s.subVam)}
						onClick={downloadReport}
					>
						<svg
							width="14px"
							height="14px"
							viewBox="0 0 14 14"
							version="1.1"
							xmlns="http://www.w3.org/2000/svg"
							xmlnsXlink="http://www.w3.org/1999/xlink"
						>
							<g
								id="资产"
								stroke="none"
								stroke-width="1"
								fill="none"
								fill-rule="evenodd"
							>
								<g
									id="监测任务管理-Web安全监测详情-漏洞"
									transform="translate(-1337.000000, -101.000000)"
									fill="#0B6FD6"
									fill-rule="nonzero"
								>
									<g id="编组-6" transform="translate(227.000000, 97.000000)">
										<g id="编组-5" transform="translate(1110.000000, 0.000000)">
											<g
												id="218下载、导入"
												transform="translate(0.000000, 4.000000)"
											>
												<path
													d="M3.64583333,8.16666667 L6.41666667,8.16666667 L6.41666667,0 L7.58333333,0 L7.58333333,8.16666667 L10.3541667,8.16666667 L7,11.6666667 L3.64583333,8.16666667 Z M14,7 L12.8333333,7 L12.8333333,12.8333333 L1.16666667,12.8333333 L1.16666667,7 L0,7 L0,14 L14,14 L14,7 Z"
													id="形状"
												></path>
											</g>
										</g>
									</g>
								</g>
							</g>
						</svg>
						<span className={cn(s.pr_t_1, s.ml8, s.cp)}>下载报告</span>
					</div>
				</div>
			)}
			<div className={s.header}>
				<div className={s.left}>
					<SecurityRating score={detail.level === '未知' ? '' : detail.score} />
				</div>
				<div className={s.right}>
					<Label className={s.labelDetail}>Web安全监测</Label>
					<div className={s.info}>
						<div className={cn(s.mb10)}>
							{Object.keys(infoObj)
								.slice(0, 2)
								.map((e, i) => {
									return (
										<span className={cn(s.vam, s.w50p)} key={e}>
											<span className={s.infoName}>{infoObj[e]}</span>：
											<span className={s.infoVal} title={detail[e]}>
												{detail[e] || '- -'}
											</span>
										</span>
									);
								})}
						</div>
						<div className={cn(s.df, s.aic)}>
							{Object.keys(infoObj)
								.slice(2)
								.map((e, i) => {
									return (
										<span className={cn(s.vam, s.w50p)} key={e}>
											<span className={s.infoName}>{infoObj[e]}</span>：
											<span className={s.infoVal}>
												{detail[e] || '- -'}
											</span>
										</span>
									);
								})}
						</div>
					</div>
					<div className={s.rBox}>
						<div className={cn(s.df, s.aic, s.jcsb)}>
							<p className={cn(s.df, s.aic)}>
								<IconS />
								<span className={s.ml12}>监测结果</span>
								<Helper
									overlay="同步资产最新一次Web安全监测结果。"
									placement="top"
								/>
							</p>
						</div>
						{row?.is_checked ? (
							(detail?.level === '未知' && statusMap[detail?.target_status?.status]) ? <p>
								{`检测${detail?.url_count}个URL地址，`}
								{`您的资产安全处于${detail?.level}状态，`}
								{statusMap[detail?.target_status?.status]}
								<SequenceDialog className={'h20 lh20'} target_status={{
									http: {...detail?.target_status?.httpGetSequence, target_status: detail?.target_status?.httpGetSequence ? detail?.target_status?.status : '' },
									ping: {...detail?.target_status?.detailPing, target_status: detail?.target_status?.httpGetSequence ? detail?.target_status?.status : '' },
								}} />
							</p> : <p style={{ lineHeight: 0.5 }} className='pt16'>
								<span
									dangerouslySetInnerHTML={{ __html: resDemo(detail.result) }}
									className={cn(s.infoVal, s.w100p, 'lh24')}
								></span>
								{detail?.is_display_url && <UrlDetailDialog className={'ml5'} id={detail?.job_id} overview={detail} type='job' buttonText='查看URL详情' />}
							</p>

						) : (
							<p className={cn(s.infoVal, s.w100p)}>
								该资产还未进行安全监测，处于未知状态，您可前往“任务管理 -
								Web安全监测”下发监测任务。
							</p>
						)}
					</div>
				</div>
			</div>
			<div className={s.infoBody}>
				<div className={cn(s.df, s.aic, s.jcsb)}>
					<Label className={cn(s.labelDetail, s.df, s.aic)}>详情</Label>
				</div>
				{row && (
					<Tabs className={s.tabs} activeKey={activeKey} onChange={changeTabs}>
						<TabPane key="vul" tab="Web漏洞">
							<VulTable
								tid={row.task?.vul_result_id && row.task?.vul_result_status ? row.task?.vul_result_id : false}
								jobId={row.job_id}
								checked={row.task?.vul_task_checked}
								target={row.target_url}
								isSchedule={row.web_security_schedule_task}
								targetStatusTableTip={(data, title) => getTableTip(data, title)}
								changeOverview={setRefresh}
							/>
						</TabPane>
						<TabPane key="ssl" tab="SSL安全">
							<SSLTable
								targetUrl={row.target_url}
								tid={row.task?.ssl_result_id && row.task?.ssl_result_status ? row.task?.ssl_result_id : false}
								jobId={row.job_id}
								checked={row.task?.ssl_task_checked}
								target={row.target_url}
								isSchedule={row.web_security_schedule_task}
								targetStatusTableTip={(data, title) => getTableTip(data, title)}
								changeOverview={setRefresh}
							/>
						</TabPane>
						<TabPane key="security" tab="安全事件">
							<SecurityTable
								changeOverview={setRefresh}
								checked={row.task?.security_event_task_checked}
								isSchedule={row.web_security_schedule_task}
								tid={row.task?.security_event_result_id && row.task?.security_event_result_status ? row.task?.security_event_result_id : false}
								jobId={row.job_id}
								target={row.target_url}
								targetStatusTableTip={(data, title) => getTableTip(data, title)}
							/>
						</TabPane>
						<TabPane key="content" tab="内容违规">
							<ContentTable
								changeOverview={setRefresh}
								checked={row.task?.content_task_checked}
								isSchedule={row.web_security_schedule_task}
								tid={row.task?.content_result_id && row.task?.content_result_status ? row.task?.content_result_id : false}
								jobId={row.job_id}
								target={row.target_url}
								targetStatusTableTip={(data, title) => getTableTip(data, title)}
							/>
						</TabPane>
						<TabPane key="changeCheck" tab="篡改">
							<ChangeCheckTable
								changeOverview={setRefresh}
								checked={row.task?.change_check_task_checked}
								isSchedule={row.web_security_schedule_task}
								tid={row.task?.change_check_result_id && row.task?.change_check_result_status ? row.task?.change_check_result_id : false}
								jobId={row.job_id}
								target={row.target_url}
								targetStatusTableTip={(data, title) => getTableTip(data, title)}
							/>
						</TabPane>
						<TabPane key="available" tab="可用性">
							<Available
								tasks={row.task}
								jobId={row.job_id}
								target={row.target_url}
							/>
						</TabPane>
						<TabPane key="asset" tab="资产变动">
							<Change row={row} hisChangeTaskId={hisChangeTaskId}></Change>
						</TabPane>
						<TabPane key="info" tab="信息">
							<Info row={row}></Info>
						</TabPane>
					</Tabs>
				)}
			</div>

			<KDialog
				title="提示"
				className={s.w400}
				maskClosable={false}
				visible={progressVisible}
				confirmText=""
				cancelText=""
				onhide={() => {
					setProgressVisible(false);
					clearInterval(downloadTimer.current);
					setDownloadPercent(0);
				}}
			>
				<div className={cn(s.p24, s.tac)}>
					<p>正在导出报告，请稍等···</p>
					<p>进度：{downloadPercent}%</p>
					<Progress percent={downloadPercent + '%'}></Progress>
				</div>
			</KDialog>
		</div>
	);
}
JobDetail.propTypes = {
	assetType: PropTypes.any,
	row: PropTypes.any,
	location: PropTypes.any,
	history: PropTypes.shape({
		push: PropTypes.func.isRequired,
		replace: PropTypes.func.isRequired,
	}).isRequired,
};
export default JobDetail;
